//
//  ConClubShowViewController.m
//  Shengzhuli
//
//  Created by FXGuo on 2017/7/4.
//  Copyright © 2017年 kamangkeji. All rights reserved.
//

#import "ConClubShowViewController.h"
#import "ClubHeaderViewCell.h"
#import "ClubDetailViewCell.h"
#import "ActivitySignViewCell.h"
#import "ClubNetwork.h"
#import "SZLAccountHelper.h"
#import "MBProgressHUD+MJ.h"
#import <SDWebImageManager.h>
#import "ConMyClubEditViewController.h"
#import <MJRefresh.h>
#import "ConPublicNearViewController.h"
#import "NearActivityCell.h"
#import "ConNearActivityDetailController.h"
#import "ConPublicOldViewController.h"
#import "ConOldActivityDetailController.h"
#import "SingleNetService.h"
#import "ConNearAcInfoViewController.h"
#import "ClubShowImageTextCell.h"

@interface ConClubShowViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) UITableView *tableView;
//选中的活动
@property (nonatomic,assign) NSInteger selectIndex;
//选中的活动按钮
@property (nonatomic,strong) UIButton *lastSelectBtn;
//右上角按钮
@property (nonatomic,weak) UIButton *editBtn;
@property (nonatomic,strong) ClubModel *model;
//是否显示关注
@property (nonatomic,assign) BOOL isShowFocus;
@property (nonatomic,assign) NSInteger nearPage;
@property (nonatomic,assign) NSInteger oldPage;

@end

@implementation ConClubShowViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的俱乐部";
    self.selectIndex = 0;
    self.tableView.mj_footer.hidden = YES;
    if (self.source == ClubShowSourceHome) {//显示关注
        self.isShowFocus = YES;
    }else {
        [self setNavi];
    }
    [self getMyClubDetail];
    //做修改近期活动 往期活动 刷新用的
//    __WEAK
//    self.refreshBlock = ^(NSInteger tag) {
//        if (tag == 1) {
//            weakSelf.nearPage = 1;
//            [weakSelf.model.nearActivities removeAllObjects];
//            [weakSelf getNearActivityList];
//        }else {
//            weakSelf.oldPage = 1;
//            [weakSelf.model.oldActivities removeAllObjects];
//            [weakSelf getOldActivityList];
//        }
//    };
}
- (void)setNavi
{
    UIButton *editBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 50, 30)];
    [editBtn setTitle:@"编辑" forState:UIControlStateNormal];
    editBtn.tag = 0;
    [editBtn setTitleColor:RGBColor(255, 121, 201) forState:UIControlStateNormal];
    editBtn.titleLabel.font = Font(16);
    [editBtn addTarget:self action:@selector(editClick:) forControlEvents:UIControlEventTouchUpInside];
    self.editBtn = editBtn;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:editBtn];
}
- (void)editClick:(UIButton *)btn
{
    if (btn.tag == 0) {
        ConMyClubEditViewController *editVc = [[ConMyClubEditViewController alloc]init];
        editVc.editModel = self.model;
        editVc.refreshBlock = ^{
            [self getMyClubDetail];
        };
        [self.navigationController pushViewController:editVc animated:YES];
    }else if(btn.tag == 1) {
        ConPublicNearViewController *publicVc = [[ConPublicNearViewController alloc]init];
        publicVc.clubId = self.model.ID;
        publicVc.publicNearBlock = ^{
            self.nearPage = 1;
            [self.model.nearActivities removeAllObjects];
            [self getNearActivityList];
        };
        [self.navigationController pushViewController:publicVc animated:YES];
    }else {
        ConPublicOldViewController *publicVc = [[ConPublicOldViewController alloc]init];
        publicVc.clubId = self.model.ID;
        publicVc.publicOldBlock = ^{
            self.oldPage = 1;
            [self.model.oldActivities removeAllObjects];
            [self getOldActivityList];
        };
        [self.navigationController pushViewController:publicVc animated:YES];
    }
}
#pragma mark - Table view data delegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section ==0) {
        return 0.01;
    }
    return 60;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, 60)];
        view.backgroundColor = [UIColor whiteColor];
        
        UIView *seprateLine = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, 5)];
        seprateLine.backgroundColor = RGBColorOne(240);
        [view addSubview:seprateLine];
        
        NSArray *titles = @[@"图文介绍",@"近期活动",@"往期活动"];
        float width = (ScreenW-2)/3.0;
        for (NSInteger i=0; i<titles.count; i++) {
            UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake((width+1)*i, 5, width, 50)];
            btn.tag = i;
            [btn setTitle:titles[i] forState:UIControlStateNormal];
            btn.titleLabel.font = Font(16);
            [btn setTitleColor:RGBColorOne(102) forState:UIControlStateNormal];
            [btn setTitleColor:RGBColor(255, 120, 201) forState:UIControlStateSelected];
            [btn addTarget:self action:@selector(selectClick:) forControlEvents:UIControlEventTouchUpInside];
            [view addSubview:btn];
            if (i == self.selectIndex) {
                btn.selected = YES;
                self.lastSelectBtn = btn;
            }
            if (i != titles.count-1) {
                UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(width+(i+width)*i, 10, 1, 40)];
                lineView.backgroundColor = RGBColorOne(200);
                [view addSubview:lineView];
            }
        }
        seprateLine = [[UIView alloc]initWithFrame:CGRectMake(0, 55, ScreenW, 5)];
        seprateLine.backgroundColor = RGBColorOne(240);
        [view addSubview:seprateLine];
        return view;
    }
    return nil;
}
- (void)selectClick:(UIButton *)btn
{
    if (btn == self.lastSelectBtn) return;
    [self hideNoDataLab];
    btn.selected = YES;
    self.lastSelectBtn.selected = NO;
    self.lastSelectBtn = btn;
    self.selectIndex = btn.tag;
    self.editBtn.tag = btn.tag;
    
    if (btn.tag == 0) {
        [self.editBtn setTitle:@"编辑" forState:UIControlStateNormal];
        self.tableView.mj_footer.hidden = YES;
        [self.model.details removeAllObjects];
        [self getImageTitleDetailWithID:self.model.ID];
    }else if (btn.tag == 1) {
        [self.editBtn setTitle:@"发布" forState:UIControlStateNormal];
        self.nearPage = 1;
        [self.model.nearActivities removeAllObjects];
        [self getNearActivityList];
        self.tableView.mj_footer.hidden = NO;
    }else{
        [self.editBtn setTitle:@"发布" forState:UIControlStateNormal];
        self.oldPage = 1;
        [self.model.oldActivities removeAllObjects];
        [self getOldActivityList];
        self.tableView.mj_footer.hidden = NO;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return [self getFirstCellH];
    }
    if (self.selectIndex == 0) {
        ImageTitleModel *model = self.model.details[indexPath.row];
        if (model.cellH) {
            return model.cellH;
        }
        ClubShowImageTextCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ClubShowImageTextCell class])];
        CGFloat cellH = [cell calculateDetailCellHWithModel:model];
        model.cellH = cellH;
        return cellH;
    }else if (self.selectIndex == 1) {
        return 120;
    }
    return 120;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    if (self.selectIndex == 0) {
        return self.model.details.count;
    }else if (self.selectIndex == 1) {
        return self.model.nearActivities.count;
    }
    return self.model.oldActivities.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        ClubHeaderViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ClubHeaderViewCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.model;
        cell.isShowFocus = self.isShowFocus;
        if (self.source == ClubShowSourceHome) {
            cell.addFocusBlcok = ^(ClubModel *model,UIButton *btn) {
                [self addFocus:btn model:model];
            };
        }
        return cell;
    }
    if (self.selectIndex == 0) {
        ClubShowImageTextCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ClubShowImageTextCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.model.details[indexPath.row];
        return cell;
    }else if (self.selectIndex == 1) {
        NearActivityCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([NearActivityCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.model.nearActivities[indexPath.row];
        return cell;
    }else {
        ActivitySignViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ActivitySignViewCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.model.oldActivities[indexPath.row];
        return cell;
    }
    return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) return;//从首页禁止点击头像
    if (self.selectIndex == 1) {
        ConNearAcInfoViewController *infoVc = [[ConNearAcInfoViewController alloc]init];
        ActivityDetailModel *model = self.model.nearActivities[indexPath.row];
        infoVc.ID = model.ID;
        [self.navigationController pushViewController:infoVc animated:YES];
    }else if (self.selectIndex == 2) {
        ConOldActivityDetailController *detailVc = [[ConOldActivityDetailController alloc]init];
        OldActivityModel *model = self.model.oldActivities[indexPath.row];
        detailVc.ID = model.ID;
        detailVc.title = model.title;
        [self.navigationController pushViewController:detailVc animated:YES];
    }
}
- (void)getMyClubDetail
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    if (self.source == OldActivitySourcePersonal) {
        parame[@"clubId"] = @"";
    }else {
        parame[@"clubId"] = @(self.clubId);
    }
    [self showClearBgWaiter];
    [ClubNetwork getMyClubDetailWithParame:parame response:^(BOOL success, NSString *msg,ClubModel *model) {
        [self hideWaiter];
        if (success) {
            self.model = model;
            NSLog(@"keepstatus = %ld",(long)self.model.keepStatus);
            if (self.source == ClubShowSourceHome) {
                self.title = model.clubName;
            }
            [self getImageTitleDetailWithID:model.ID];
        }else {
            [MBProgressHUD showError:msg];
        }
    }];
}
- (void)getImageTitleDetailWithID:(NSInteger)ID
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"clubId"] = @(ID);
    [self showClearBgWaiter];
    [ClubNetwork getClubImageTitleDetailWithParame:parame response:^(BOOL success, NSString *msg,NSArray *lists) {
        if (success) {
            [self.model.details addObjectsFromArray:lists];
            [self calculateImagesHeight:self.model.details];
        }else {
            [self hideWaiter];
            [MBProgressHUD showError:msg];
        }
    }];
}
//缓存图片计算图片高度
- (void)calculateImagesHeight:(NSArray *)arr
{
    __WEAK
    dispatch_group_t group = dispatch_group_create();
    for (ImageTitleModel *model in arr) {
        dispatch_group_enter(group);
        [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:model.clubImage] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
            dispatch_group_leave(group);
        }];
    }
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [weakSelf hideWaiter];//下载完图片在隐藏指示器
        [self.view addSubview:self.tableView];
        [weakSelf.tableView reloadData];
    });
}
- (void)getNearActivityList
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"pageNo"] = @(self.nearPage);
    parame[@"clubId"] = @(self.model.ID);
    [self showClearBgWaiter];
    [ClubNetwork getNearActivityListWithParame:parame response:^(BOOL success, NSString *msg, NSArray *lists) {
        [self hideWaiter];
        [self.tableView.mj_footer endEditing:YES];
        [self hideNoDataLab];
        if (success) {
            self.tableView.mj_footer.hidden = (lists.count < 20);
            if (self.nearPage == 1&&lists.count == 0) {
                [self showNoDataLab:self.tableView range:CGRectMake(0, [self getFirstCellH]+100, ScreenW, 20) title:@"暂无活动"];
            }
            [self.model.nearActivities addObjectsFromArray:lists];
            [self.tableView reloadData];
        }else {
            [MBProgressHUD showError:msg];
        }
    }];
}
- (void)getOldActivityList
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"pageNo"] = @(self.oldPage);
    parame[@"clubId"] = @(self.model.ID);
    [self showClearBgWaiter];
    [ClubNetwork getOldSelfActivityListWithParame:parame response:^(BOOL success, NSString *msg, NSArray *lists) {
        [self hideWaiter];
        [self.tableView.mj_footer endEditing:YES];
        [self hideNoDataLab];
        if (success) {
            self.tableView.mj_footer.hidden = (lists.count < 20);
            if (self.oldPage == 1&&lists.count == 0) {
                [self showNoDataLab:self.tableView range:CGRectMake(0, [self getFirstCellH]+100, ScreenW, 20) title:@"暂无活动"];
            }
            [self.model.oldActivities addObjectsFromArray:lists];
            [self.tableView reloadData];
        }else {
            [MBProgressHUD showError:msg];
        }
    }];
}

- (void)addFocus:(UIButton *)btn model:(ClubModel *)model
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    parame[@"clubId"] = @(model.ID);
    [SingleNetService addFocusParame:parame response:^(BOOL success, NSString *msg) {
        if (success) {
            if (success&&!btn.selected) {
                [self showOnlyText:@"关注成功"];
                btn.selected = YES;
            }else if (success&&btn.selected){
                [self showOnlyText:@"取消关注成功"];
                btn.selected = NO;
            }
        }else {
            [MBProgressHUD showError:msg];
        }
    }];
}

- (CGFloat)getFirstCellH
{
    CGFloat cellH = [self.model.content boundingRectWithSize:CGSizeMake(ScreenW-30, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:Font(14)} context:nil].size.height+237;
    return cellH;
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenW,ScreenH-SafeAreaTopHeight) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ClubHeaderViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([ClubHeaderViewCell class])];
        [_tableView registerClass:[ClubShowImageTextCell class] forCellReuseIdentifier:NSStringFromClass([ClubShowImageTextCell class])];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([NearActivityCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([NearActivityCell class])];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ActivitySignViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([ActivitySignViewCell class])];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            if (self.selectIndex == 1) {
                self.nearPage++;
                [self getNearActivityList];
            }else if (self.selectIndex == 2) {
                self.oldPage++;
                [self getOldActivityList];
            }
        }];
    }
    return _tableView;
}


@end
